import querystring from "querystring"
import { myAlert } from "../utils/alert";
let baseUrl = "";
// if (process.env.NODE_ENV === "development") {
//     baseUrl = "/api"
// }

//响应拦截
function response(url, res) {
    //打印数据
    console.log('本次请求：' + baseUrl + url);
    console.log(res);
    //失败处理
    if (res.code !== 200) {
        myAlert(res.msg)
        return;
    }
    

}
/**
 * url:"/api/login"
 * params:{phone:11,password:123}----->phone=11&password=123
*/
export const get = (url, params = {}) => {
    //先将参数转换
    params = querystring.stringify(params);
    return new Promise((resolve) => {
        fetch(baseUrl + url + "?" + params, {
            headers: {
                authorization: localStorage.getItem("token")
            }
        }).then(res => res.json()).then(res => {
            //响应拦截
            response(url, res)
            resolve(res)
        })
    })
}
/**
 * url:"/api/login"
*/
export const post = (url, params = {}, isFile = false) => {
    let data = null;
    let headers = {
        authorization: localStorage.getItem("token"),

    }
    if (isFile) {
        //有文件
        data = new FormData();
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        //无文件
        data = querystring.stringify(params);
        headers = {
            ...headers,
            "Content-type": "application/x-www-form-urlencoded"
        }
    }
    return new Promise((resolve) => {
        fetch(baseUrl + url, {
            method: "post",
            body: data,
            headers
        }).then(res => res.json())
            .then(res => {
                //响应拦截
                response(url, res);

                resolve(res)
            })
    })
}